<template>
  <div class="data-collector">
    <el-card class="collector-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon size="20" color="#2e7d32"><DataAnalysis /></el-icon>
          <span>{{ title }}</span>
          <el-tag v-if="dataCount > 0" type="success" size="small">
            已收集 {{ dataCount }} 条数据
          </el-tag>
        </div>
      </template>
      
      <div class="collector-content">
        <!-- 数据收集表单 -->
        <div class="collector-form">
          <h3 class="form-title">数据录入</h3>
          <FormBuilder
            ref="formRef"
            :fields="formFields"
            :model-value="formData"
            :rules="formRules"
            :submit-loading="submitLoading"
            @submit="handleFormSubmit"
            @reset="handleFormReset"
          />
        </div>
        
        <!-- 数据预览 -->
        <div class="data-preview">
          <div class="preview-header">
            <h3 class="preview-title">数据预览</h3>
            <div class="preview-actions">
              <el-button 
                size="small" 
                @click="exportData"
                :disabled="dataList.length === 0"
              >
                <el-icon><Download /></el-icon>
                导出数据
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="clearAllData"
                :disabled="dataList.length === 0"
              >
                <el-icon><Delete /></el-icon>
                清空数据
              </el-button>
            </div>
          </div>
          
          <!-- 数据统计 -->
          <div class="data-stats">
            <el-row :gutter="16">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ dataList.length }}</div>
                  <div class="stat-label">总数据量</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ todayCount }}</div>
                  <div class="stat-label">今日新增</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ validDataCount }}</div>
                  <div class="stat-label">有效数据</div>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <!-- 数据表格 -->
          <el-table 
            :data="dataList" 
            border 
            stripe 
            size="small"
            max-height="400"
            class="data-table"
          >
            <el-table-column 
              v-for="field in displayFields" 
              :key="field.name"
              :prop="field.name" 
              :label="field.label"
              :width="field.width"
              :min-width="field.minWidth"
            >
              <template #default="{ row }">
                <div class="cell-content">
                  <!-- 文本内容 -->
                  <span v-if="field.displayType === 'text' || !field.displayType">
                    {{ formatCellValue(row[field.name], field) }}
                  </span>
                  
                  <!-- 标签显示 -->
                  <el-tag 
                    v-else-if="field.displayType === 'tag'"
                    :type="getTagType(row[field.name], field)"
                    size="small"
                  >
                    {{ formatCellValue(row[field.name], field) }}
                  </el-tag>
                  
                  <!-- 状态显示 -->
                  <el-tag 
                    v-else-if="field.displayType === 'status'"
                    :type="getStatusType(row[field.name])"
                    size="small"
                  >
                    {{ formatCellValue(row[field.name], field) }}
                  </el-tag>
                  
                  <!-- 评分显示 -->
                  <el-rate 
                    v-else-if="field.displayType === 'rate'"
                    :model-value="row[field.name]"
                    :max="field.max || 5"
                    disabled
                    show-score
                  />
                  
                  <!-- 进度条显示 -->
                  <el-progress 
                    v-else-if="field.displayType === 'progress'"
                    :percentage="row[field.name]"
                    :status="getProgressStatus(row[field.name])"
                  />
                  
                  <!-- 文件链接 -->
                  <el-link 
                    v-else-if="field.displayType === 'file'"
                    type="primary"
                    :href="row[field.name]"
                    target="_blank"
                  >
                    <el-icon><Document /></el-icon>
                    查看文件
                  </el-link>
                  
                  <!-- 图片显示 -->
                  <el-image 
                    v-else-if="field.displayType === 'image'"
                    :src="row[field.name]"
                    :preview-src-list="[row[field.name]]"
                    fit="cover"
                    style="width: 40px; height: 40px; border-radius: 4px;"
                  />
                </div>
              </template>
            </el-table-column>
            
            <!-- 操作列 -->
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row, $index }">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="editData(row, $index)"
                >
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="deleteData($index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div v-if="dataList.length > pageSize" class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="dataList.length"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑数据" 
      width="600px"
      @close="handleEditDialogClose"
    >
      <FormBuilder
        ref="editFormRef"
        :fields="formFields"
        :model-value="editingData"
        :rules="formRules"
        :show-actions="false"
      />
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditData">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DataAnalysis, Download, Delete, Document, Edit, Search, Plus, ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import FormBuilder from './FormBuilder.vue'

// 表单字段类型
interface FormField {
  name: string
  label: string
  type: string
  required?: boolean
  span?: number
  placeholder?: string
  options?: Array<{ label: string; value: any }>
  rules?: any[]
  
  // 显示相关
  displayType?: 'text' | 'tag' | 'status' | 'rate' | 'progress' | 'file' | 'image'
  width?: number | string
  minWidth?: number | string
  max?: number
  tagTypes?: Record<string, string>
  statusTypes?: Record<string, string>
}

// 组件属性
interface Props {
  title?: string
  fields: FormField[]
  initialData?: any[]
  autoSave?: boolean
  storageKey?: string
  pageSize?: number
}

// 组件事件
interface Emits {
  (e: 'data-change', data: any[]): void
  (e: 'data-add', item: any): void
  (e: 'data-edit', item: any, index: number): void
  (e: 'data-delete', index: number): void
  (e: 'data-export', data: any[]): void
}

const props = withDefaults(defineProps<Props>(), {
  title: '数据收集器',
  initialData: () => [],
  autoSave: true,
  storageKey: 'data-collector',
  pageSize: 10
})

const emit = defineEmits<Emits>()

// 表单引用
const formRef = ref()
const editFormRef = ref()

// 表单数据
const formData = reactive<Record<string, any>>({})

// 数据列表
const dataList = ref<any[]>([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(props.pageSize)

// 编辑相关
const editDialogVisible = ref(false)
const editingData = reactive<Record<string, any>>({})
const editingIndex = ref(-1)

// 提交状态
const submitLoading = ref(false)

// 计算属性
const dataCount = computed(() => dataList.value.length)

const todayCount = computed(() => {
  const today = new Date().toDateString()
  return dataList.value.filter(item => {
    const itemDate = new Date(item.createdAt || item.timestamp || Date.now()).toDateString()
    return itemDate === today
  }).length
})

const validDataCount = computed(() => {
  if (!props.fields || !Array.isArray(props.fields)) {
    return 0;
  }

  return dataList.value.filter(item => {
    // 检查必填字段是否都有值
    return props.fields.every(field => {
      if (field.required) {
        const value = item[field.name]
        return value !== undefined && value !== null && value !== ''
      }
      return true
    })
  }).length
})

const displayFields = computed(() => {
  if (!props.fields || !Array.isArray(props.fields)) {
    return [];
  }

  return props.fields.filter(field => field.name !== 'id')
})

// 表单验证规则
const formRules = computed(() => {
  const rules: Record<string, any> = {}
  
  if (!props.fields || !Array.isArray(props.fields)) {
    return rules;
  }

  props.fields.forEach(field => {
    if (field.required) {
      rules[field.name] = [
        { required: true, message: `请输入${field.label}`, trigger: 'blur' }
      ]
    }
    
    if (field.rules) {
      rules[field.name] = [...(rules[field.name] || []), ...field.rules]
    }
  })
  
  return rules
})

// 初始化表单数据
const initFormData = () => {
  // 确保 fields 存在
  if (!props.fields || !Array.isArray(props.fields)) {
    return;
  }

  props.fields.forEach(field => {
    if (formData[field.name] === undefined) {
      switch (field.type) {
        case 'checkbox':
          formData[field.name] = []
          break
        case 'switch':
          formData[field.name] = false
          break
        case 'rate':
          formData[field.name] = 0
          break
        case 'slider':
          formData[field.name] = field.max ? field.max / 2 : 50
          break
        case 'number':
          formData[field.name] = 0
          break
        default:
          formData[field.name] = ''
      }
    }
  })
}

// 加载数据
const loadData = () => {
  if (props.storageKey) {
    const saved = localStorage.getItem(props.storageKey)
    if (saved) {
      try {
        dataList.value = JSON.parse(saved)
      } catch (error) {
        console.error('加载保存数据失败:', error)
      }
    }
  }
  
  if (props.initialData.length > 0) {
    dataList.value = [...props.initialData, ...dataList.value]
  }
}

// 保存数据
const saveData = () => {
  if (props.storageKey && props.autoSave) {
    localStorage.setItem(props.storageKey, JSON.stringify(dataList.value))
  }
}

// 表单提交
const handleFormSubmit = async (data: Record<string, any>) => {
  try {
    // 添加时间戳和ID
    const newItem = {
      ...data,
      id: Date.now().toString(),
      createdAt: new Date().toISOString(),
      timestamp: Date.now()
    }
    
    // 添加到数据列表
    dataList.value.unshift(newItem)
    
    // 保存数据
    saveData()
    
    // 重置表单
    formRef.value?.resetFields()
    initFormData()
    
    // 发送事件
    emit('data-add', newItem)
    emit('data-change', [...dataList.value])
    
    ElMessage.success('数据添加成功')
  } catch (error) {
    console.error('添加数据失败:', error)
    ElMessage.error('添加数据失败')
  }
}

// 表单重置
const handleFormReset = () => {
  initFormData()
}

// 编辑数据
const editData = (row: any, index: number) => {
  editingIndex.value = index
  Object.assign(editingData, row)
  editDialogVisible.value = true
}

// 保存编辑数据
const saveEditData = async () => {
  try {
    await editFormRef.value?.validate()
    
    // 更新数据
    Object.assign(dataList.value[editingIndex.value], {
      ...editingData,
      updatedAt: new Date().toISOString()
    })
    
    // 保存数据
    saveData()
    
    // 关闭对话框
    editDialogVisible.value = false
    
    // 发送事件
    emit('data-edit', editingData, editingIndex.value)
    emit('data-change', [...dataList.value])
    
    ElMessage.success('数据更新成功')
  } catch (error) {
    console.error('更新数据失败:', error)
  }
}

// 删除数据
const deleteData = async (index: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条数据吗？',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const deletedItem = dataList.value.splice(index, 1)[0]
    
    // 保存数据
    saveData()
    
    // 发送事件
    emit('data-delete', index)
    emit('data-change', [...dataList.value])
    
    ElMessage.success('数据删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除数据失败:', error)
      ElMessage.error('删除数据失败')
    }
  }
}

// 清空所有数据
const clearAllData = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有数据吗？此操作不可恢复！',
      '清空确认',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    dataList.value = []
    
    // 保存数据
    saveData()
    
    // 发送事件
    emit('data-change', [])
    
    ElMessage.success('数据已清空')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空数据失败:', error)
      ElMessage.error('清空数据失败')
    }
  }
}

// 导出数据
const exportData = () => {
  try {
    const dataStr = JSON.stringify(dataList.value, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${props.title}-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    // 发送事件
    emit('data-export', [...dataList.value])
    
    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 编辑对话框关闭
const handleEditDialogClose = () => {
  editingIndex.value = -1
  Object.keys(editingData).forEach(key => {
    delete editingData[key]
  })
}

// 格式化单元格值
const formatCellValue = (value: any, field: FormField) => {
  if (value === undefined || value === null) return '-'
  
  switch (field.displayType) {
    case 'date':
      return new Date(value).toLocaleDateString()
    case 'datetime':
      return new Date(value).toLocaleString()
    case 'number':
      return Number(value).toLocaleString()
    case 'percentage':
      return `${value}%`
    default:
      return String(value)
  }
}

// 获取标签类型
const getTagType = (value: any, field: FormField) => {
  if (field.tagTypes && field.tagTypes[value]) {
    return field.tagTypes[value]
  }
  return 'info'
}

// 获取状态类型
const getStatusType = (value: any) => {
  const statusMap: Record<string, string> = {
    'active': 'success',
    'inactive': 'info',
    'pending': 'warning',
    'error': 'danger',
    'success': 'success',
    'failed': 'danger'
  }
  return statusMap[value] || 'info'
}

// 获取进度条状态
const getProgressStatus = (value: number) => {
  if (value >= 100) return 'success'
  if (value >= 80) return 'warning'
  if (value >= 60) return ''
  return 'exception'
}

// 监听数据变化
watch(dataList, saveData, { deep: true })

// 初始化
onMounted(() => {
  initFormData()
  loadData()
})

// 暴露方法
defineExpose({
  addData: (data: any) => {
    const newItem = {
      ...data,
      id: Date.now().toString(),
      createdAt: new Date().toISOString(),
      timestamp: Date.now()
    }
    dataList.value.unshift(newItem)
    saveData()
    return newItem
  },
  getData: () => [...dataList.value],
  clearData: clearAllData,
  exportData
})
</script>

<style scoped>
.data-collector {
  width: 100%;
}

.collector-card {
  border-radius: 12px;
  border: 1px solid var(--border-color);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
}

.collector-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 32px;
  margin-top: 24px;
}

.collector-form,
.data-preview {
  background: var(--background-secondary);
  padding: 24px;
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.form-title,
.preview-title {
  margin: 0 0 20px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.preview-actions {
  display: flex;
  gap: 8px;
}

.data-stats {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: var(--primary-color);
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: var(--text-secondary);
  margin-top: 8px;
}

.data-table {
  margin-bottom: 20px;
}

.cell-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 20px;
}

@media (max-width: 1200px) {
  .collector-content {
    grid-template-columns: 1fr;
    gap: 24px;
  }
}
</style>
